package com.ep.general.instruktor.kartypracy;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.ep.general.GeneralClassMdt;
import com.ep.general.instruktor.kartypracy.db.KartaPracy;

public class KartaPracyMdt extends GeneralClassMdt<KartaPracy> {

	public KartaPracyMdt() {
		super(KartaPracy.class);
	}

	public boolean isDataUnique(Date data) {
		getSession().beginTransaction();
		Criteria crit = getSession().createCriteria(KartaPracy.class);
		crit.add(Restrictions.eq("data", data));
		return list(crit).size() == 0;
	}

	public List<KartaPracy> getKarty(int instruktorId) {
		getSession().beginTransaction();
		Criteria crit = getSession().createCriteria(KartaPracy.class);
		crit.add(Restrictions.eq("instruktor.id", instruktorId));
		crit.addOrder(Order.desc("data"));

		return list(crit);
	}

	public List<KartaPracy> getbyMonth(int instruktorId) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT * FROM i_d_karty_pracy WHERE MONTH(data) = ");
		sb.append(Calendar.getInstance().get(Calendar.MONTH) + 1);
		sb.append(" AND d_instruktor_id=");
		sb.append(instruktorId);
		sb.append(" AND YEAR(data) = ");
		sb.append(Calendar.getInstance().get(Calendar.YEAR));
		sb.append(" ORDER BY data DESC");

		getSession().beginTransaction();
		SQLQuery query = getSession().createSQLQuery(sb.toString());
		query.addEntity(KartaPracy.class);

		return list(query);
	}

	public List<KartaPracy> getByWeek(int instruktorId) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT * FROM i_d_karty_pracy");
		sb.append(" WHERE data >= CURDATE()");
		sb.append(" AND data <= DATE_ADD(CURDATE(), INTERVAL 7 DAY) AND d_instruktor_id=");
		sb.append(instruktorId);
		sb.append(" AND YEAR(data) = ");
		sb.append(Calendar.getInstance().get(Calendar.YEAR));
		sb.append(" ORDER BY data DESC");

		getSession().beginTransaction();
		SQLQuery query = getSession().createSQLQuery(sb.toString());
		query.addEntity(KartaPracy.class);

		return list(query);
	}
}
